require 'Qt4'
load 'ui_datehoureditor.rb'

class DateHourEditorCallback < Qt::Widget
	attr_accessor :db
	attr_accessor :week
	attr_accessor :day
	
	slots  'time_changed(QTime)'
	
	def init(db,week,day,widget)
		@db=db
		@week=week
		@day=day
		widget.setTime(@db.getWeeklyFreeHours().getFreeHoursByWeekAndDay(week,day))
		Qt::Object.connect(widget,SIGNAL("timeChanged(QTime)"),self,SLOT("time_changed(QTime)"))
	end
	
	def time_changed(time)
		@db.getWeeklyFreeHours().setFreeHours(@week,@day,time)
	end
end

class DateHourEditor < Qt::MainWindow
	attr_accessor :ui
	attr_accessor :db
	attr_accessor :callbacks
	
	slots  'date_changed(QDate)'

	def init(db)
		@ui=Ui_DateHourEditor.new
        @ui.setupUi(self)
		self.show()
		@db=db
		
		@ui.datePivotWeek.setDate(@db.getWeeklyFreeHours().getPivotWeek())
		
		labelgroups = Array.new
		# Some stupid code
		labelgroups << @ui.txt11
		labelgroups << @ui.txt12
		labelgroups << @ui.txt13
		labelgroups << @ui.txt14
		labelgroups << @ui.txt15
		labelgroups << @ui.txt16
		labelgroups << @ui.txt17
		
		labelgroups << @ui.txt21
		labelgroups << @ui.txt22
		labelgroups << @ui.txt23
		labelgroups << @ui.txt24
		labelgroups << @ui.txt25
		labelgroups << @ui.txt26
		labelgroups << @ui.txt27
		
		callbacks = Array.new
		#Set groups
		i=0
		labelgroups.each { 
		|x|      
		callback=DateHourEditorCallback.new
		#@ui.centralwidget.addWidget(callback)
		callback.init(@db, i.div(7), i % 7, x)
		callbacks << callback
		i=i+1
	    }
		#Set first week
		@ui.datePivotWeek.setDate(@db.getWeeklyFreeHours().getFirstWeek())
		Qt::Object.connect(@ui.datePivotWeek,SIGNAL("dateChanged(QDate)"),self,SLOT("date_changed(QDate)"))
	end
	
	def date_changed(qdate)
	    date=@ui.datePivotWeek.date()
		new_pivot=@db.getWeeklyFreeHours().setFirstWeekMonday( date )
		@ui.datePivotWeek.setDate( new_pivot )
	end
end